package logic

import (
	"context"
	"fmt"
	"info-hub/cache"
	"info-hub/model"

	"info-hub/inforpc/inforpc"
	"info-hub/inforpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *inforpc.RegisterRequest) (*inforpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line
	var user model.User
	model.DB.Where("account", in.Account).Find(&user)
	if user.ID != 0 {
		return nil, fmt.Errorf("用户已注册请登录")
	}
	result, err := cache.Rdb.Get(cache.Ctx, "SenSms"+in.Account).Result()
	if err != nil {
		return nil, err
	}
	if result != in.SenSmsCode {
		return nil, fmt.Errorf("验证码错误")
	}
	user = model.User{
		Account:  in.Account,
		Password: in.Password,
		Avatar:   in.Avatar,
		Add:      in.Add,
		Name:     in.Name,
	}
	return &inforpc.RegisterResponse{
		UserId: int64(user.ID),
	}, nil
}
